package com.leo.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author du
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        // 判断是不是http request请求
        if (msg instanceof HttpRequest) {
            System.out.println("msg类型: " + msg.getClass().getSimpleName());
            System.out.println("客户端地址: " + ctx.channel().remoteAddress());


            //过滤favicon.ico
            if(new URI(((HttpRequest) msg).uri()).getPath().equals("/favicon.ico")) {
                System.out.println("favicon.ico 不做响应");
                return;
            }

            //回复客户端消息
            ByteBuf buf = Unpooled.copiedBuffer("hello, 我是服务端", CharsetUtil.UTF_8);

            //构造http响应
            HttpResponse response  = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

            //返回response对象
            ctx.channel().writeAndFlush(response);
            //ctx.writeAndFlush(response)
        }
    }
}